import { IRootState } from "@/store/types"

import { Module } from "vuex"
import { ISystemState, IRequestType } from "./types"
import { pageListData } from "@/service/main/system/system"

// 查询请求对象
const requireObj: any = {
  user: "/users/list",
  role: "/role/list",
  goods: "/goods/list",
  menu: "/menu/list"
}

const systemModule: Module<ISystemState, IRootState> = {
  namespaced: true,
  state() {
    return {
      userList: [],
      userCount: 0,
      roleList: [],
      roleCount: 0,
      goodsList: [],
      goodsCount: 0,
      menuList: [],
      menuCount: 0
    }
  },
  mutations: {
    changeUserList(commit, userList: any[]) {
      commit.userList = userList
    },
    changeUserCount(commit, userCount: number) {
      commit.userCount = userCount
    },
    changeRoleList(commit, roleList: any[]) {
      commit.roleList = roleList
    },
    changeRoleCount(commit, roleCount: number) {
      commit.roleCount = roleCount
    },
    changeGoodsList(commit, goodsList: any[]) {
      commit.goodsList = goodsList
    },
    changeGoodsCount(commit, goodsCount: number) {
      commit.goodsCount = goodsCount
    },
    changeMenuList(commit, menusList: any[]) {
      commit.menuList = menusList
    },
    changeMenuCount(commit, menuCount: number) {
      commit.menuCount = menuCount
    }
  },
  getters: {
    // 获取页面的请求
    pageListData(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}List`]
      }
    },
    // 获取总条数
    pageListCount(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Count`]
      }
    }
  },
  //请求页面的数据
  actions: {
    async getPageListAction({ commit }, payload: any) {
      const pageName = payload.pageName
      const pageUrl = requireObj[pageName]
      // 1 发送页面请求
      const pageResult = await pageListData(pageUrl, payload.queryInfo)
      const { list, totalCount } = pageResult.data

      // 2 将数据储存到state
      const stateName = pageName.slice(0, 1).toUpperCase() + pageName.slice(1, pageName.length)

      commit(`change${stateName}List`, list)
      commit(`change${stateName}Count`, totalCount)
    }
  }
}

export default systemModule
